const app = getApp()
import util from '../../../utils/util'
import {
  GetIsseuMembers,
  GetEventCatList,
  GetGriderVisit,
  GetGriderMemberList,
  UpEvent,
  UpVisist

} from '../../../config/api'

Page({
  data: {
    grider_storge: {}, // 网格员测试缓存信息

    imgs: [],
    count: 0,
    compressImgsSizeArr: [],

    event_level: '',
    level_index: 0,
    levelArr: [{
        id: 1,
        title: '普通事件'
      },
      {
        id: 2,
        title: '重点事件'
      }
    ],

    events: [{
      ucid: '',
      event_level: 1,
      uid: '',
      u_name: '',
      addr: '',
      content: '',
      attach: [],
      puid: '',
      p_name: '',
      vollege_id: '',
      town_id: ''
    }], // 事件数组

    event_index: '',
    eventArr: [], // 事件数组

    // visit_index: '',
    // visitArr: [], // 走访数组
    party_index: '',
    // partyArr: [], // 当事人
    allName: [], // 当事人
    uid: '',
    u_name: '',
    addr: '', // 事件地点
    content: '', // 事件内容
    isShowNamePopup: false, // 是否显示姓名弹出
    showView: true, // 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let grider_storge = wx.getStorageSync('grider')
    this.setData({
      'events[0].uid': grider_storge.id,
      'events[0].u_name': grider_storge.name,
      'events[0].vollege_id': grider_storge.vollege_id,
      'events[0].town_id': grider_storge.town_id,
      'events[0].puid': grider_storge.id,
      'events[0].p_name': grider_storge.name,
      grider_storge: grider_storge // 正式打开，测试注释
    })

    this.getEventType()
    // this.getVisit()
    //  this.getGriderMember()
  },

  getEventType() { // 获取事件类型
    let that = this;
    util.apiRequest(GetEventCatList, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('事件类型', r)
      that.setData({
        eventArr: r.data.data
      })
    })
  },

  onShowEventPopup() { // 显示事件类型弹层
    this.setData({
      showView: false
    })
  },

  onSelectEvent(e) { // 选择事件类型
    let event_index = e.currentTarget.dataset.event_index;
    // let event_id = e.currentTarget.dataset.event_id;
    console.log('event_index', event_index)
    console.log('事件名称：', this.data.eventArr[event_index].title)
    let ucid = this.data.eventArr[event_index].id;

    this.setData({
      showView: true,
      'events[0].ucid': ucid,
      event_index: event_index,
    })
  },

  bindChangeLevel: function(e) {
    console.log('事件等级：', e.detail.value)
    let event_level = this.data.levelArr[e.detail.value].id


    this.setData({
      level_index: e.detail.value,
      'events[0].event_level': event_level
    })

    console.log('等级events:', this.data.events)
  },


  // getVisit() { // 获取网格员走访记录
  //   let that = this;
  //   let id = this.data.grider_storge.id;
  //   util.apiRequest(GetGriderVisit, {
  //     id: id
  //   },null).then(r => {
  //     console.log('走访记录', r)
  //     that.setData({
  //       visitArr: r.data.data.data
  //     })
  //   })
  // },

  // getGriderMember() { // 获取当事人
  //   let that = this;
  //   let id = this.data.grider_storge.id;
  //   util.apiRequest(GetGriderMemberList, {
  //     id: id
  //   }, null).then(r => {
  //     console.log('当事人', r)
  //     that.setData({
  //       partyArr: r.data.data
  //     })
  //   })
  // },

  // onSelectName() { // 选择当事人，弹出框
  //   this.setData({
  //     isShowPopup: true
  //   })
  // },

  onSearchName(e) { // 输入搜索当事人
    console.log(e)
    let name = e.detail.value;
    console.log('name', name)
    if (name != '') {
      this.setData({
        isShowNamePopup: true
      })
      util.apiRequest(GetIsseuMembers, {
        id: this.data.grider_storge.id,
        name: name,
        vollege_id: app.globalData.vollege_id
      }, null).then(r => {
        console.log('搜索：', r)
        this.setData({
          allName: r.data.data
        })
      })
    } else {
      this.setData({
        tname: '',
        isShowNamePopup: false
      })
    }
  },

  onConfirmName(e) { // 点击确认当事人
    console.log('选择姓名', e)
    let uid = e.currentTarget.dataset.id;
    let u_name = e.currentTarget.dataset.name;
    let committees = e.currentTarget.dataset.committees;
    let address = e.currentTarget.dataset.address;

    this.setData({
      isShowNamePopup: false,
      'events[0].uid': uid,
      'events[0].u_name': u_name,
      'events[0].addr': committees + address
    })

    // this.setData({
    //   uid,
    //   u_name,
    //   isShowNamePopup: false,
    //   addr: committees + address
    // })

    console.log('55events:', this.data.events)
  },

  // onConfirmName(e) {
  //   console.log('选择姓名', e)
  //   let uid = e.currentTarget.dataset.id;
  //   let u_name = e.currentTarget.dataset.name;
  //   let committees = e.currentTarget.dataset.committees;
  //   //  let address = e.currentTarget.dataset.address;
  //   this.setData({
  //     isShowPopup: false,
  //     uid,
  //     u_name,
  //     addr: committees
  //   })
  // },

  // bindChangeEvent: function(e) {
  //   console.log('事件类型：', e.detail.value)
  //   this.setData({
  //     event_index: e.detail.value
  //   })
  // },

  // bindChangeVisit: function(e) {
  //   console.log('访问', e.detail.value)
  //   this.setData({
  //     visit_index: e.detail.value
  //   })
  // },

  // bindChangeParty: function(e) {
  //   console.log('当事人', e.detail.value)
  //   this.setData({
  //     party_index: e.detail.value,
  //     addr: this.data.partyArr[e.detail.value].committees + this.data.partyArr[e.detail.value].address
  //   })
  // },

  inputAddr(e) {
    this.setData({
      'events[0].addr': e.detail.value
    })
    console.log('地点events', this.data.events)
    // this.setData({
    //   addr: e.detail.value
    // })
  },

  inputContent(e) {
    console.log(e.detail.value)
    this.setData({
      'events[0].content': e.detail.value
    })
    console.log('内容events', this.data.events)
    // this.setData({
    //   content: e.detail.value
    // })
  },

  formSubmit() {
    // console.log('事件比较：', this.data.event_index.length == 0)
    // if (this.data.event_index.length == 0) {
    //   wx.showModal({
    //     showCancel: false,
    //     content: '请选择事件类型',
    //   })
    //   return;
    // }

    if(this.data.events[0].ucid == ''){
      wx.showModal({
        showCancel: false,
        content: '请选择事件类型',
      })
      return;
    }

    // vvv 2020-11-23 不要当事人
    // if (this.data.u_name == '') { 
    //   wx.showModal({
    //     showCancel: false,
    //     content: '请选择当事人',
    //   })
    //   return;
    // }

    let content = this.data.events[0].content.replace(/(^\s*)|(\s*$)/g, "");
    if (!content) {
      wx.showModal({
        showCancel: false,
        content: '请填写内容',
      })
      return;
    }

    let that = this;

    let params = {
      nick_name: that.data.grider_storge.nick_name,
      type: 1, // 有事件
      uid: that.data.grider_storge.id, // 走访人id
      u_name: that.data.grider_storge.name, // 走访人姓名
      vollege_id: that.data.grider_storge.vollege_id,
      town_id: that.data.grider_storge.town_id,
      events: that.data.events
    }
    console.log('提交参数：', params)

    util.apiRequest(UpVisist, params).then(r => {
      console.log('11提交结果：', r)
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: r.data.info,
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/pages/grid/visit/visit"
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: r.data.info,
          icon: 'none',
          duration: 2000
        })
      }
    })


    // let params = {
    //   event_level:this.data.levelArr[this.data.level_index].id, // 事件等级
    //   nick_name: this.data.grider_storge.nick_name,
    //   cat_id: 2,
    //   ucid: this.data.eventArr[this.data.event_index].id,
    //   // vid: this.data.visitArr[this.data.visit_index].id,
    //   uid: this.data.uid, // 2020-11-23 不要当事人
    //   u_name: this.data.u_name, // 2020-11-23 不要当事人
    //   content: this.data.content,
    //   attach: this.data.imgs,
    //   addr: this.data.addr,
    //   vollege_id: this.data.grider_storge.vollege_id,
    //   town_id: this.data.grider_storge.town_id,
    //   helper: this.data.grider_storge.id,
    //   puid: this.data.grider_storge.id,
    //   p_name: this.data.grider_storge.name,
    //   h_name: this.data.grider_storge.name
    // }
    // console.log('参数：', params)

    // util.apiRequest(UpEvent, params).then(r => {
    //   console.log('提交后', r)
    //   if (r.data.code == 1) {
    //     wx.showModal({
    //       showCancel: false,
    //       content: r.data.info,
    //       success(res) {
    //         if (res.confirm) {
    //           wx.redirectTo({
    //             url: "/pages/grid/grid"
    //           })
    //         }
    //       }
    //     })
    //   } else {
    //     wx.showToast({
    //       title: r.data.info,
    //       icon: 'none',
    //       duration: 2000
    //     })
    //   }
    // })

  },

  // 上传图片
  chooseImg: function(e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 750,
                maxHeight = 500;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function() {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.4,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              'events[0].attach': that.data.imgs,
                              imgs: that.data.imgs
                            })
                            console.log('图片44', that.data.events)
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 500)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },

  // 预览图片
  previewImg: function(e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})